package com.uphone.kingmall.login;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.personal.set.AgreementActivity;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.LoginBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.DeviceUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.PhoneFormatCheckUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.StringUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2018/07/31
 *     desc   :注册
 *     version: 1.0
 * </pre>
 */
public class RegisterActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_get_yzm)
    TextView tvGetYzm;
    @BindView(R.id.et_yzm)
    EditText etYzm;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_pwd_confirm)
    EditText etPwdConfirm;
    @BindView(R.id.et_invite_code)
    EditText etInviteCode;
    @BindView(R.id.btn_queding)
    Button btnQueding;
    @BindView(R.id.cb_check)
    CheckBox cbCheck;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @IntentData
    private String invite = "";

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_register;
    }

    @Override
    public void initView() {
        if (!TextUtils.isEmpty(invite)) {
            etInviteCode.setText(invite + "");
        }
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.iv_back, R.id.tv_get_yzm, R.id.btn_queding, R.id.tv_xieyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_get_yzm:
                getMachCode();

                break;
            case R.id.tv_xieyi:

                openActivity(AgreementActivity.class);
                break;
            case R.id.btn_queding:
                register();
                break;
        }
    }

    private void getMachCode() {

        if (TextUtils.isEmpty(etPhone.getText().toString())) {
            showShortToast("手机号不能为空");
            return;
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(etPhone.getText().toString())) {
            showShortToast("手机号不正确");
            return;
        }

        DeviceUtil.sendSmsCode(this, etPhone.getText().toString().trim(), "1", new DeviceUtil.DeviceCodeCallBack() {
            @Override
            public void callBack(String deviceCode) {
                timer.start();
                tvGetYzm.setEnabled(false);
                tvGetYzm.setTextColor(Color.parseColor("#cccccc"));
            }
        });

    }

    private void register() {
        if (!cbCheck.isChecked()) {
            showShortToast("请选择是否同意《用户注册协议》");
            return;
        }
        if (TextUtils.isEmpty(etPhone.getText().toString()) || TextUtils.isEmpty(etPwd.getText().toString())
                || TextUtils.isEmpty(etPwdConfirm.getText().toString())
                || TextUtils.isEmpty(etYzm.getText().toString())) {
            showShortToast("请填写完整数据");
            return;
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(etPhone.getText().toString())) {
            showShortToast("手机号不正确");
            return;
        }
        if (etPwd.getText().toString().trim().length() < 6 || etPwd.getText().toString().trim().length() > 20) {
            showShortToast("请将密码限制在6-20位之间");
            return;
        }
        if (!StringUtils.isLetterDigit(etPwd.getText().toString().trim())) {
            showShortToast("密码格式不正确");
            return;
        }
        if (!etPwd.getText().toString().trim().equals(etPwdConfirm.getText().toString().trim())) {
            showShortToast("两次密码不一致");
            return;
        }
        if (!cbCheck.isChecked()) {
            showShortToast("请勾选《用户注册协议》");
            return;
        }
        HttpParams params = new HttpParams();
        params.put("loginname", etPhone.getText().toString().trim());
        params.put("code", etYzm.getText().toString().trim());
        params.put("password", etPwd.getText().toString().trim());
        if (!TextUtils.isEmpty(etInviteCode.getText().toString())) {
            params.put("inviteCode", etInviteCode.getText().toString().trim());
        }
        OkGoUtils.progressRequest(MyUrl.register, RegisterActivity.this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                LoginBean bean = GsonUtils.getGson().fromJson(response, LoginBean.class);
                if (bean.getUser() != null) {
                    LoginBean.UserBean user = bean.getUser();
                    SharedPreferencesHelper.saveToken(user.getToken());
                    SharedPreferencesHelper.saveUserName(user.getUserName());
                    SharedPreferencesHelper.saveUserPhone(user.getUserMobile());
                    SharedPreferencesHelper.saveUserId(user.getUserId());
                    SharedPreferencesHelper.saveUserImg(user.getUserPhoto());
//                    JpushUtil.setTagAndAlias(RegisterActivity.this, user.getUserId());
//                    CommonUtil.loginRY();
                    KeyboardUtils.hideSoftInput(RegisterActivity.this);
                }
                if (bean.getCode() == 0) {
                    ToastUtils.showShortToast(RegisterActivity.this, "注册成功！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ActivityCollector.removeAll(MainActivity.class);
                            finish();
                        }
                    }, 500);
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });

    }

    /**
     * 倒计时
     */
    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long l) {
            tvGetYzm.setText(l / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tvGetYzm.setEnabled(true);
            tvGetYzm.setText("重新获取");
            tvGetYzm.setTextColor(Color.parseColor("#E33344"));
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
